import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { login as loginApi } from '@/apis/auth.js'

export function useLogin() {
  const router = useRouter()
  const route = useRoute()
  const loading = ref(false)
  
  // 表单数据
  const loginForm = reactive({
    username: 'admin',
    password: '123456',
    rememberMe: false
  })
  
  // 表单验证规则
  const loginRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 1, max: 20, message: '用户名长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 1, max: 20, message: '密码长度在 1 到 20 个字符', trigger: 'blur' }
    ]
  }
  
  // 处理登录
  const handleLogin = async () => {
    loading.value = true
    try {
      // 调用后端登录接口
      const response = await loginApi(loginForm)
      
      // 根据后端返回的数据结构获取信息
      // 假设后端返回格式：{ code: 200, message: 'success', data: { token: 'xxx', username: 'xxx', roleType: 'xxx' } }
      const { code, message, data } = response
      
      if (code === 200 && data) {
        // 存储token
        localStorage.setItem('token', data.token)
        
        // 存储用户信息
        const userInfo = {
          username: data.username,
          roleType: data.roleType
        }
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        
        // 如果勾选了记住密码，存储用户名
        if (loginForm.rememberMe) {
          localStorage.setItem('username', loginForm.username)
        } else {
          localStorage.removeItem('username')
        }
        
        ElMessage.success('登录成功')
        
        // 处理重定向
        const redirect = route.query.redirect || '/'
        router.push(redirect)
      } else {
        throw new Error(message || '登录失败，请重试')
      }
    } catch (error) {
      // 处理错误情况
      if (error.response && error.response.data) {
        // 服务器返回的错误
        ElMessage.error(error.response.data.message || '登录失败，请重试')
      } else {
        // 其他错误
        ElMessage.error(error.message || '网络错误，请稍后重试')
      }
    } finally {
      loading.value = false
    }
  }
  
  // 初始化表单（从localStorage读取保存的用户名）
  const initForm = () => {
    const savedUsername = localStorage.getItem('username')
    if (savedUsername) {
      loginForm.username = savedUsername
      loginForm.rememberMe = true
    }
  }
  
  return {
    loginForm,
    loginRules,
    loading,
    handleLogin,
    initForm
  }
}